<?php

namespace plugin\admin\app\controller;

use app\services\OrderService;
use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\ExpressCompany;
use plugin\admin\app\model\PrizeDrawActivity;
use plugin\admin\app\model\PrizeDrawGood;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserProfile;
use plugin\admin\app\model\UserPropertyLog;
use support\Request;
use support\Response;
use plugin\admin\app\model\UserPrizeDraw;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 抽奖明细 
 */
class UserPrizeDrawController extends Crud
{
    
    /**
     * @var UserPrizeDraw
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new UserPrizeDraw;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(Request $request): Response
    {
        return view('user-prize-draw/index', [
            'aid' => $request->get('id')
        ]);
    }

    public function export(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $limit = 99999999;
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('user-prize-draw/insert');
    }

    public function express(Request $request)
    {
        try {
            $order = UserPrizeDraw::where('order_no', $request->get('order_no'))->first();
            $list = OrderService::expressInfo($order);
        } catch (\Exception $e) {
            $list = ['list' => []];
        }

        return view('order/express', [
            'list' => $list
        ]);
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        if (!Auth::isSupperAdmin() && $this->dataLimit && !empty($data[$this->dataLimitField])) {
            $admin_id = $data[$this->dataLimitField];
            if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                throw new BusinessException('无数据权限');
            }
        }
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }
        unset($data[$primary_key]);

        $data['shipping_time'] = date('Y-m-d H:i:s');

        if (!empty($data['express_company'])) {
            $expressCompany = ExpressCompany::where('id', $data['express_company'])->first();
            $data['express_company'] = $expressCompany['express_name'];
            $data['order_status'] = UserPrizeDraw::ORDER_STATUS_WAIT_RECEIVE;
        }

        return [$id, $data];
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('user-prize-draw/update');
    }

    public function show(Request $request)
    {
        $id = $request->get('id');

        $orderInfo = UserPrizeDraw::where('id', $id)->first();

        $orderInfo['address_info'] = json_decode($orderInfo['address_info'], true);
        $orderInfo['level_text'] = PrizeDrawGood::getLevelText($orderInfo['level']);

        $info = PrizeDrawGood::where('aid', $orderInfo['aid'])->where('level', $orderInfo['level'])->first()->toArray();
        $orderInfo['goods_info'] = json_decode($info['goods_info'], true);

        return view('user-prize-draw/show', [
            'orderInfo' => $orderInfo
        ]);
    }

    protected function formatNormal($items, $total): Response
    {
        $userIds = array_column($items, 'user_id');
        $activityIds = array_column($items, 'aid');

        $users = UserProfile::whereIn('user_id', $userIds)->get()->keyBy('user_id');
        $activities = PrizeDrawActivity::whereIn('id', $activityIds)->get()->keyBy('id');

        foreach ($items as $key=>$item) {
            $items[$key]['user'] = $users[$item['user_id']] ?? [];
            $items[$key]['activity'] = $activities[$item['aid']] ?? [];
            $items[$key]['level_text'] = PrizeDrawGood::getLevelText($item['level']);
            $items[$key]['order_status_text'] = UserPrizeDraw::getOrderStatusText($item['order_status']);
            $items[$key]['status_text'] = UserPrizeDraw::getStatusText($item['status']);
            $addressInfo = json_decode($item['address_info'], true);
            $items[$key]['address_info'] = join('', [
                'province' => $addressInfo['province'] ?? '',
                'city' => $addressInfo['city'] ?? '',
                'district' => $addressInfo['district'] ?? '',
                'address' => $addressInfo['address'] ?? '',
                'contact_name' => $addressInfo['contact_name'] ?? '',
                'contact_mobile' => $addressInfo['contact_mobile'] ?? '',
            ]);
            $items[$key]['title'] = PrizeDrawActivity::buildTitle($activities[$item['aid']]);
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }
}
